package com.sakura.demo.common.utils;

import com.alibaba.fastjson.JSON;
import com.sakura.demo.common.model.JsonResponseEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @Author: zhengcan
 * @Date: 2022/5/4
 * @Description: web工具类
 * @Version: 1.0.0 创建
 */
@Slf4j
public class WebResponseUtils {

    /**
     * 封装响应体
     * @param response
     * @param json
     * @return
     */
    public static String renderString(HttpServletResponse response, String json, int status) {
        try {
            response.setStatus(status);
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.setContentLength(json.getBytes(StandardCharsets.UTF_8).length);
            response.setCharacterEncoding("utf-8");
            response.getWriter().println(json);
        } catch (IOException e) {
            log.error("输出Response响应值异常，errorMsg={}", e.getMessage());
        }
        return null;
    }

    public static void responseFailed(HttpServletResponse response, String jsonBody) {
        renderString(response, jsonBody, HttpStatus.INTERNAL_SERVER_ERROR.value());
    }

    public static void responseSuccess(HttpServletResponse response, String jsonBody) {
        renderString(response, jsonBody, HttpStatus.OK.value());
    }

    public static void responseJsonEntityFailed(HttpServletResponse response, String msg) {
        responseJsonEntityFailed(response, HttpStatus.INTERNAL_SERVER_ERROR.value(), msg);
    }

    public static void responseJsonEntityFailed(HttpServletResponse response, int status, String msg) {
        JsonResponseEntity<Object> result = new JsonResponseEntity(msg, status);
        renderString(response, JSON.toJSONString(result), HttpStatus.INTERNAL_SERVER_ERROR.value());
    }

    public static void responseJsonEntitySuccess(HttpServletResponse response, String msg) {
        JsonResponseEntity<Object> result = new JsonResponseEntity(msg, HttpStatus.OK.value());
        renderString(response, JSON.toJSONString(result), HttpStatus.OK.value());
    }
}
